package com.sinoglobal.ningxia.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.Toast;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.beans.LoadingVo;
import com.sinoglobal.ningxia.beans.LockingCheck;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.MyAsyncTask;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.AnalyticsConfig;

import cn.jpush.android.api.JPushInterface;

/**
 * @author qiwx
 * @createdate 2014-6-10 下午4:03:23
 * @Description:load页，图片后台可配置
 */
public class LoadingActivity extends BaseActivity {

    protected static final String FIRST_LOGIN = "first_login";
    private ImageView loading;// 启动页
    private ImageView ad;// 广告页
    private Bitmap defaultLoading;// 启动页默认图
    // private Bitmap defaultAd;// 广告业默认图
    // private InputStream adIs = null;
    // private Handler mHandler;
    private Animation loadingAni;
    private Animation adAni;
    // private ItktAsyncTaskWithDialog<Void, Void, Void> task;
    private long mSleep = 1000;// 睡眠时间
    // AssetManager assets;
    private Context mContext;
    private String saveStartImg = "startImg";
    private String saveAdvImg = "advImg";

    // private Bitmap deImg;
    // ProgressDialog pd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        isTemplate = false;
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.loading_layout);
        if (TextUtil.stringIsNull(SharedPreferenceUtil.getString(this,
                MContants.CHANNEL_ID))) {
            String channelId = AnalyticsConfig
                    .getChannel(FlyApplication.context);
            if (TextUtil.stringIsNotNull(channelId))
                SharedPreferenceUtil.saveString(this, MContants.CHANNEL_ID,
                        channelId);
        }

        mContext = this;

        // 对接用户中心，拿明文的过度版本。需要安装新版本后登陆一次
        if (!SharedPreferenceUtil.getBoolean(LoadingActivity.this, FIRST_LOGIN)) {
            SharedPreferenceUtil.saveString(LoadingActivity.this, "id",
                    MContants.EMPTY_STRING);
            SharedPreferenceUtil.saveString(LoadingActivity.this, "photo",
                    MContants.EMPTY_STRING);
            SharedPreferenceUtil.saveString(LoadingActivity.this, "sex",
                    MContants.EMPTY_STRING);
            SharedPreferenceUtil.saveString(LoadingActivity.this, "nickname",
                    MContants.EMPTY_STRING);
            SharedPreferenceUtil.saveString(LoadingActivity.this, "score",
                    MContants.EMPTY_STRING);
            SharedPreferenceUtil.saveString(LoadingActivity.this, "photo",
                    MContants.EMPTY_STRING);
            SharedPreferenceUtil.saveBoolean(LoadingActivity.this, FIRST_LOGIN,
                    true);
            // SinoStore.getInstance(this, userId, userName, nickName, score)
        }

        if (!TextUtil.stringIsNull(SharedPreferenceUtil.getString(
                LoadingActivity.this, "id"))) {
            String userId = SharedPreferenceUtil.getString(
                    LoadingActivity.this, "id");
            lockingCheck(userId);
        }

        init();
        if (EquipmentUtil.checkNetState(this)) {
            showImg();
        } else {

            String url = SharedPreferenceUtil.getString(mContext,
                    saveStartImg);
            if (url != null && !"".equals(url)) {
                Picasso.with(LoadingActivity.this).load(url).placeholder(R.drawable.loading_ad_image).error(R.drawable.loading_ad_image).into(loading);
            } else {
                Picasso.with(LoadingActivity.this).load(R.drawable.loading_start_image).into(loading);
            }


            new Thread() {
                public void run() {
                    try {
                        sleep(mSleep);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    hander.sendEmptyMessage(1);
                }
            }.start();
        }
    }

    private void lockingCheck(final String id) {
        new MyAsyncTask<Void, Void, LockingCheck>(LoadingActivity.this, false) {

            @Override
            public LockingCheck before(Void... params) throws Exception {
                return RemoteImpl.getInstance().getLockingCheckNews(id);
            }

            @Override
            public void after(LockingCheck result) {
                if ("2".equals(result.getStatus())) {
                    SharedPreferenceUtil.saveString(LoadingActivity.this, "id",
                            MContants.EMPTY_STRING);
                    SharedPreferenceUtil.saveString(LoadingActivity.this,
                            "photo", MContants.EMPTY_STRING);
                    SharedPreferenceUtil.saveString(LoadingActivity.this,
                            "sex", MContants.EMPTY_STRING);
                    SharedPreferenceUtil.saveString(LoadingActivity.this,
                            "nickname", MContants.EMPTY_STRING);
                    SharedPreferenceUtil.saveString(LoadingActivity.this,
                            "score", MContants.EMPTY_STRING);
                    SharedPreferenceUtil.saveString(LoadingActivity.this,
                            "photo", MContants.EMPTY_STRING);
                    FlyApplication.userId = "";
                    Toast.makeText(FlyApplication.context, "账号已锁定", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void exception() {
                // TODO Auto-generated method stub

            }
        }.execute();
    }

    // 下载图片

    private Handler hander = new Handler() {

        /**
         * @author qiwx
         * @createdate 2014-7-16 上午10:11:04
         * @Description:
         * @type
         * @throws Exception
         * @parameters
         */
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    FlyUtil.intentForward(LoadingActivity.this, MainActivity.class);
                    finish();
                    break;
            }
        }

    };

    private void init() {
        // 动画效果
        loadingAni = AnimationUtils.loadAnimation(this, R.anim.anim_alpha_out);
        adAni = AnimationUtils.loadAnimation(this, R.anim.anim_alpha_in);
        loading = (ImageView) findViewById(R.id.img_loading);
        ad = (ImageView) findViewById(R.id.img_ad);
        finishAnim = true;
        // assets = getAssets();

		/*
         * if (defaultAd != null) ad.setImageBitmap(defaultAd);
		 */
        setSynAndPushSwitchData();
        setAutoLoginData();
    }

    // 设置同步共享和推送消息的默认开关值，同步共享默认为关，消息推送默认为开
    private void setSynAndPushSwitchData() {
        if (SharedPreferenceUtil.getBoolean(FlyApplication.context,
                "isCollectSyn"))
            return;
        SharedPreferenceUtil.saveBoolean(FlyApplication.context,
                "isCollectSyn", false);// 收藏时同步共享
        SharedPreferenceUtil.saveBoolean(FlyApplication.context,
                "isCommentSyn", false);// 评论时同步共享
        if (SharedPreferenceUtil.getBoolean(FlyApplication.context,
                "isPushMessageCheck"))
            return;
        SharedPreferenceUtil.saveBoolean(FlyApplication.context,
                "isMessagePush", true);// 消息推送
        SharedPreferenceUtil.saveBoolean(FlyApplication.context,
                "isActivityPush", true);// 活动相关消息推送
    }

    // 设置自动登录默认为选中
    private void setAutoLoginData() {
        if (SharedPreferenceUtil
                .getBoolean(FlyApplication.context, "autoLogin")) {
            return;
        }
        SharedPreferenceUtil.saveBoolean(FlyApplication.context, "autoLogin",
                true);
    }

    /**
     * @author sbk
     * @createdate 2014-5-29 上午11:19:02
     * @Description: 显示活动图片
     */
    private void showImg() {
        new ItktOtherAsyncTask<Void, Void, LoadingVo>(false) {

            @Override
            public LoadingVo before(Void... params) throws Exception {
                return RemoteImpl.getInstance().getLoading();
            }

            @Override
            public void after(final LoadingVo result) {
                if (Code.CODE_SUCCESS != result.getCode()) {
                    FlyUtil.intentForward(LoadingActivity.this,
                            MainActivity.class);
                    finish();
                    return;
                }

                if (result.getStart_img() != null
                        && (!result.getStart_img().equals(
                        MContants.EMPTY_STRING))) {
                    String url = ConnectionUtil.localUrl
                            + result.getStart_img();
                    SharedPreferenceUtil
                            .saveString(mContext, saveStartImg, url);
                    if (url != null && !"".equals(url)) {
                        Picasso.with(LoadingActivity.this).load(url).placeholder(R.drawable.loading_ad_image).error(R.drawable.loading_ad_image).into(loading);
                    } else {
                        Picasso.with(LoadingActivity.this).load(R.drawable.loading_start_image).into(loading);
                    }

                    loading.startAnimation(loadingAni);
                    ad.setVisibility(View.GONE);
                } else {
                    FlyUtil.intentForward(LoadingActivity.this,
                            MainActivity.class);
                    finish();
                }

                loadingAni.setAnimationListener(new AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {

                        if (result.getAd_img() != null
                                && (!result.getAd_img().equals(
                                MContants.EMPTY_STRING))) {
                            loading.setVisibility(View.GONE);
                            ad.setVisibility(View.VISIBLE);
                            String url = ConnectionUtil.localUrl
                                    + result.getAd_img();
                            SharedPreferenceUtil.saveString(mContext,
                                    saveAdvImg, url);
                            if (url != null && !"".equals(url)) {
                                Picasso.with(LoadingActivity.this).load(url).placeholder(R.drawable.loading_ad_image).error(R.drawable.loading_ad_image).into(ad);
                            } else {
                                Picasso.with(LoadingActivity.this).load(R.drawable.loading_ad_image).into(ad);
                            }
                            ad.startAnimation(adAni);
                        } else {
                            FlyUtil.intentForward(LoadingActivity.this,
                                    MainActivity.class);
                            finish();
                        }

                    }
                });

                adAni.setAnimationListener(new AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {

                        FlyUtil.intentForward(LoadingActivity.this,
                                MainActivity.class);
                        finish();

                    }
                });
            }

            @Override
            public void exception() {
                FlyUtil.intentForward(LoadingActivity.this, MainActivity.class);
                finish();
            }
        }.execute();
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        JPushInterface.onPause(this);
    }
}
